package hzn;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class TestZk {
    String url="hzn100:2181,hzn101:2181";
    int timeout=2000;
    ZooKeeper client;
    @Before
    public void init()throws Exception{
        /*
        w.process();
        new Thread(){
            run(){
                阻塞，直到收到zk通知事件，才继续
                w.process();
            }
        }
        * */

        client=new ZooKeeper(url, timeout, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                List<String>childs;
                System.out.println("=============begin============");
                try{
                    //目的是为了能持续监听指定节点的子节点的增删
                    childs=client.getChildren("/",true);
                    for(String c:childs){
                        System.out.println(c);
                    }
                    System.out.println("==========end==========");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Test
    public void createNode()throws Exception{
        Thread.sleep(3000);
        String path=client.create("/servers","hello".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println("path:"+path);
        Thread.sleep(Long.MAX_VALUE);
    }

    @Test
    public void deleteAnddModifyAndRead()throws Exception{
        Stat s=client.exists("/servers",false);
        System.out.println("存在servers节点吗？"+(s!=null));
        int version=s.getVersion();//获取版本号
        System.out.println("版本号："+version);
        if(s!=null) {//存在，下面删除
            //client.delete("/servers",0);//如果不知道版本号是多少就写0
            client.setData("/servers","嘿嘿rrfrrr".getBytes(),version);
            //读取数据
            System.out.println(new String(client.getData("/servers",false,null)));
        }
        Thread.sleep(Long.MAX_VALUE);
    }
}
